//
//  NFindTableViewController.m
//  News
//
//  Created by zhangtao on 2018/10/7.
//  Copyright © 2018年 zt.td. All rights reserved.
//

#import "NFindTableViewController.h"
#import "NItemSearchView.h"

#import "NFindTableHeaderView.h"
#import "NMainOneImgCell.h"
#import "NMainThreeImgCell.h"
#import "NMainNoImgCell.h"
#import "NSearchViewController.h"
#import "NFindDetailViewController.h"
#import "NArticleModel.h"

@interface NFindTableViewController ()
#define oneImgIdentifier @"oneImgIdentifier"
#define threeImgIdentifier @"threeImgIdentifier"
#define noImgIdentifier @"noImgIdentifier"

@property(nonatomic,assign)NSInteger cp;   //当前页
@property(nonatomic,assign)NSInteger hotCp; //24小时热点页数
@property(nonatomic,strong)NSMutableArray <NArticleModel *> * articles; //每次都赋值给此array
@property(nonatomic,strong)NSMutableArray <NArticleModel *> * hotArticles;  //热门
@property(nonatomic,strong)NSMutableArray <NArticleModel *> * focusArticles;  //关注
@property(nonatomic,assign)NSInteger topType;

@end

@implementation NFindTableViewController
{
    NFindTableHeaderView *headerView;
    NSInteger kind;
}
-(NFindTableHeaderView *)headerView{
    if (!headerView) {
        NOnlineFocusModel *online = [NOnlineFocusModel sharedInstance];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:online.nameArray];
        [arr insertObject:@"全部" atIndex:0];
        headerView = [[NFindTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, ACEWidth, 40) items:arr];
        headerView.findHeadfocusCallBack = ^(NSInteger tag) {
            NSString *ID = @"";
            if (tag == 0) {
                ID = online.ids;
            }else{
                ID = [NSString stringWithFormat:@"%@",online.fouceArray[tag-1]];
            }
            [self.focusArticles removeAllObjects];
            [self requestFocusArticleWithTopicId:ID];
        };
    }
    return headerView;
}

-(instancetype)initWithStyle:(UITableViewStyle)style{
    return [super initWithStyle:UITableViewStylePlain];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _cp = 1;
    _hotCp = 1;
    NItemSearchView *view = [[NItemSearchView alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-20, 44) items:@[@"关注",@"热点"]];
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    [view markBadgeIndex:1 andNum:99];
    view.ItemSearchViewCallBack = ^(NSInteger tag) {
        if (tag ==-1) {
            
        }else if (tag == -2){
            NSearchViewController *search = [[NSearchViewController alloc]init];
            search.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:search animated:YES];
        }else{
            self->kind = tag;
            
            if (tag == 0) {
                //关注
                self.topType = 0;
                
                if (self.focusArticles) {
                    self.articles = self.focusArticles;
                    [self.tableView reloadData];
                }else{
//                    [self requestFocusArticle];
                }
            }else if(tag == 1){
                //热点
                self.topType = 1;
                
                if (self.hotArticles) {
                    self.articles = self.hotArticles;
                    [self.tableView reloadData];
                }else{
                    [self request24Hot];
                }
            }
            
            [self.tableView reloadData];
        }
    };
    [self.navigationItem setTitleView:view];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NMainOneImgCell" bundle:nil] forCellReuseIdentifier:oneImgIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"NMainThreeImgCell" bundle:nil] forCellReuseIdentifier:threeImgIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"NMainNoImgCell" bundle:nil] forCellReuseIdentifier:noImgIdentifier];

    NOnlineFocusModel *onlineMOdel = [NOnlineFocusModel sharedInstance];
    if (onlineMOdel.ids) {
            [self requestFocusArticleWithTopicId:onlineMOdel.ids];
    }else{
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(firstRequestFocusSuccessNoty) name:firstRequestFocusSuccess object:nil];
    }
}

-(void)firstRequestFocusSuccessNoty{
    
    NOnlineFocusModel *onlineMOdel = [NOnlineFocusModel sharedInstance];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:onlineMOdel.nameArray];
    [arr insertObject:@"全部" atIndex:0];
    self.headerView.items = arr;
        [self requestFocusArticleWithTopicId:onlineMOdel.ids];
}

-(void)requestFocusArticleWithTopicId:(NSString *)ID{
    NSDictionary *param;
    NSString *url;
    
    //我关注的主题下的文章列表  主题ID，多个以,号分带了
//    param = @{@"token":TOKEN,@"cuid":CUID,@"tids":@"0",@"cp":@"1"};
//    url = HTTP_GET_MY_FOCE_LIST;
    
    //文章列表
    param =@{@"token":TOKEN,@"cuid":CUID,@"tids":ID,@"cp":[NSNumber numberWithInteger:_cp]};
    url = HTTP_GET_MY_FOCE_LIST;// HTTP_ARTICLE_LIST;
    
    [[NHTTPManage shareInstance]afGet:url andParam:param success:^(id  _Nonnull responseObject) {
        NSArray *arr = responseObject[@"Data"];
        if (!self.focusArticles) {
            self.focusArticles = [NSMutableArray arrayWithCapacity:0];
        }
        
        for (NSDictionary *dic in arr) {
            NArticleModel *model = [[NArticleModel alloc]initWithDic:dic];
            [self.focusArticles addObject:model];
        }
        
        self.articles = self.focusArticles;
        [self.tableView reloadData];
    } failture:^(id  _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

-(void)request24Hot{
    [[NHTTPManage shareInstance]afGet:HTTP_GET_HOT_24H andParam:@{@"cp":[NSNumber numberWithInteger:_hotCp],@"topicalID":@"0",@"num":@"10"} success:^(id  _Nonnull responseObject) {
        NSArray *arr = responseObject[@"Data"];
        if (!self.hotArticles) {
            self.hotArticles = [NSMutableArray arrayWithCapacity:0];
        }
        
        for (NSDictionary *dic in arr) {
            NArticleModel *model = [[NArticleModel alloc]initWithDic:dic];
            [self.hotArticles addObject:model];
        }
        self.articles = self.hotArticles;
        [self.tableView reloadData];
        
    } failture:^(id  _Nonnull error) {
        NSLog(@"%@",error);
    }];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section==0?0:self.articles.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return .1;
    }
    return kind == 0 ? 40 : .1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return [UIView new];
    }
    return kind == 0? self.headerView :[UIView new];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NArticleModel *article = self.articles[indexPath.row];
    NSString *coverPic = article.CoverPic;
    NSArray *coverPics = [coverPic componentsSeparatedByString:@","];
    if (coverPic.length == 0) {
        return ACEWidth*5/19;
    }else if (coverPic.length>0 && coverPics.count<3) {
        return ACEWidth*11/38;
    }else if (coverPics.count>=3){
        return ACEWidth*18/39;
    }
    
    
    
    
    if (indexPath.row == 0) {
        //380:110
        return ACEWidth*11/38;
    }
    
    if (indexPath.row == 1) {
        //390:180
        return ACEWidth*18/39;
    }
    
    if (indexPath.row == 2) {
        //380:120
        return ACEWidth*5/19;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    //和后台确定以后使用articleType确定多图单图和无图
    NArticleModel *article = self.articles[indexPath.row];
    NSString *coverPic = article.CoverPic;
    NSArray *coverPics = [coverPic componentsSeparatedByString:@","];
    if (coverPic.length == 0) {
        NMainNoImgCell *cell = [tableView dequeueReusableCellWithIdentifier:noImgIdentifier];
        cell.model = article;
        return cell;
    }else if (coverPic.length>0 && coverPics.count<3) {
        NMainOneImgCell *cell = [tableView dequeueReusableCellWithIdentifier:oneImgIdentifier];
        cell.model = article;
        return cell;
    }else if (coverPics.count>3){
        NMainThreeImgCell *cell = [tableView dequeueReusableCellWithIdentifier:threeImgIdentifier];
        cell.model = article;
        return cell;
    }
    
    /*
    if (indexPath.row == 1) {
        NMainThreeImgCell *cell = [tableView dequeueReusableCellWithIdentifier:threeImgIdentifier];
        
        return cell;
    }
    
    if (indexPath.row == 2) {
        NMainNoImgCell *cell = [tableView dequeueReusableCellWithIdentifier:noImgIdentifier];
        return cell;
    }
    */
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NFindDetailViewController *detail = [[NFindDetailViewController alloc]init];
    detail.hidesBottomBarWhenPushed = YES;
    if (_topType == 0) {
        detail.isFocue = YES;
    }else if (_topType == 1){
        detail.isFocue = NO;
    }
    detail.article = self.articles[indexPath.row];
    [self.navigationController pushViewController:detail animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
